﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Media.Imaging;

namespace Bing.Spell
{
    /// <summary>
    /// Interaction logic for SpellWindow.xaml
    /// </summary>
    public partial class SpellWindow
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="SpellWindow"/> class.
        /// </summary>
        public SpellWindow()
        {
            InitializeComponent();
        }

        private void btnCheckSpelling_Click(object sender, RoutedEventArgs e)
        {
            var appId = txtAppId.Text.Trim();
            var query = txtCheckWord.Text.Trim();
            txtResults.Text = "";
    
            if (string.IsNullOrEmpty(query))
            {
                imgWordGood.Source = null;
                return;
            }

            SearchRequest searchRequest = new SearchRequest { AppId = appId, Query = query, Market = "en-US" }; 
            SpellResponse response = API.Spell(searchRequest, new SpellRequest());

            if (response.Errors.Count > 0 )
            {
                // Display Errors
                MessageBox.Show(bingErrorMessage(response.Errors), "Bing.API Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            updateImage(response.Total == 0);
            if (response.Total > 0)
                txtResults.Text = response.Results[0].Value;

        }

        private static string bingErrorMessage(IEnumerable<Error> errors)
        {
            StringBuilder text = new StringBuilder();
            int counter = 1;
            foreach (Error error in errors)
            {
                text.AppendFormat("Error #{0}.\r\n", counter);
                text.AppendFormat("\tMessage: {0}\r\n", error.Message);
                text.AppendFormat("\tCode: {0}\r\n", error.Code);
                text.AppendFormat("\tHelpUrl: {0}\r\n", error.HelpUrl);
                text.AppendFormat("\tParameter: {0}\r\n", error.Parameter);
                text.AppendFormat("\tValue: {0}\r\n", error.Value);
                counter++;
            }

            return text.ToString();
        }

        private void updateImage (bool spelledCorrectly)
        {
            imgWordGood.Source = spelledCorrectly
                                     ? new BitmapImage(new Uri("pack://application:,,,/Images/okay.png"))
                                     : new BitmapImage(new Uri("pack://application:,,,/Images/error_x.png"));
        }
    }
}
